//
//  EntertainmentViewController.m
//  ToWhere
//
//  Created by dllo on 15/11/12.
//  Copyright © 2015年 www.TE.com. All rights reserved.
//

#import "EntertainmentViewController.h"
#import "EntertainmentView.h"
#import "DataAnalysis.h"
#import "EntertainmentModel.h"
#import "EnterTableViewCell.h"
#import <MJRefresh.h>
#import "EnterDetailViewController.h"
#import "TravelSearchViewController.h"

@interface EntertainmentViewController ()<UITableViewDataSource, UITableViewDelegate, EntertainmenteDelegate>

@property(nonatomic, retain) UIView *titleView;

@property(nonatomic, assign) NSInteger dataPage;

@property(nonatomic, retain) NSMutableArray *enterModelArray;

@property(nonatomic, retain) UITableView *tableView;

//上拉加载(数据条数)
@property(nonatomic, retain) MJRefreshAutoGifFooter *footer;

@property(nonatomic, retain) NSMutableArray *NewArray;

@property(nonatomic, assign) NSInteger index;

@end

@implementation EntertainmentViewController

- (void)dealloc
{
    [_titleView release];
    [_enterModelArray release];
    [_tableView release];
    [_footer release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化
    [self initData];
    
    //创建标题
    [self createTitle];
    
    //创建选择框
    [self createScrollLine];
    
    //解析数据
    [self loadData];
    
    //创建tableView
    [self createTableView];
    
}

-(void)initData
{
    self.enterModelArray = [NSMutableArray array];
    self.NewArray = [NSMutableArray array];
    self.index = 1;
}

#pragma mark 创建标题
-(void)createTitle
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,kHeight * 64)];
    self.titleView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.titleView];
    [self.titleView release];
    [_titleView release];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 100 * kWidth, self.titleView.frame.size.height / 2 - 10 * kHeight, kWidth * 200, kHeight * 30)];
    titleLabel.text = @"游记";
    titleLabel.font = [UIFont systemFontOfSize:17 * kWidth];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.titleView addSubview:titleLabel];
    [titleLabel release];
    
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    btn.frame = CGRectMake(10 * kWidth, self.titleView.frame.size.height / 2 - 8 * kHeight, 30 * kWidth, 30 *  kHeight);
//    [btn setBackgroundImage:[UIImage imageNamed:@"Enter_photo"] forState:UIControlStateNormal];
//    [self.titleView addSubview:btn];
    
    UIButton *btnOne = [UIButton buttonWithType:UIButtonTypeCustom];
    btnOne.frame = CGRectMake(340 * kWidth, self.titleView.frame.size.height / 2 - 7 * kHeight, 25 * kWidth, 25 *  kHeight);
    [btnOne setBackgroundImage:[UIImage imageNamed:@"Enter_sousuo"] forState:UIControlStateNormal];
    [self.titleView addSubview:btnOne];
    [btnOne addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)btnAction:(UIButton *)btn
{
    TravelSearchViewController *search = [[TravelSearchViewController alloc]init];
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:search animated:YES];
    [self setHidesBottomBarWhenPushed:NO];
}


#pragma mark 创建选择框
-(void)createScrollLine
{
    NSArray *titleArray = @[@"最热", @"最新"];
    EntertainmentView *enter = [[EntertainmentView alloc]initWithFrame:CGRectMake(0, 64 * kHeight, self.view.frame.size.width, 40 * kHeight) Array:titleArray];
    enter.backgroundColor = [UIColor colorWithRed:0.882 green:0.882 blue:0.902 alpha:1];
    enter.delegate = self;
    [self.view addSubview:enter];
    [enter release];
}

//代理方法
-(void)buttonOfScrollLineClicked:(UIButton *)sender
{
    NSLog(@"%ld", sender.tag);
    if (sender.tag == 5000) {
        self.index = 1;
        [self.tableView removeFromSuperview];
        [self loadData];
        [self createTableView];
    }
    else
    {
        self.index = 0;
        [self.tableView removeFromSuperview];
        [self loadData];
        [self createTableView];
    }
}

#pragma mark 解析数据
-(void)loadData
{
    if (self.index == 1) {
        [DataAnalysis dataAnalysisGETWithUrlString:[NSString stringWithFormat:@"http://chanyouji.com/api/trips/featured.json?page=%ld", self.dataPage] parameters:nil showHuD:YES hiddenView:nil successfulBlock:^(id responseObject) {
            
            for (NSDictionary *dic in responseObject) {
                EntertainmentModel *enter = [EntertainmentModel enterWithDictionary:dic];
                [self.enterModelArray addObject:enter];
            }
            
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
        } failureBlock:^(NSError *error) {
            
            NSLog(@"ERROR: %@" , error);
        }];
    }
    else
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        NSDate *nowDate = [NSDate date];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *strDate = [[formatter stringFromDate:nowDate] substringToIndex:7];
        [self.NewArray removeAllObjects];
        for (int i = 0; i < 10; i++) {
            [DataAnalysis dataAnalysisGETWithUrlString:[NSString stringWithFormat:@"http://chanyouji.com/api/trips/featured.json?page=%d", i + 1] parameters:nil showHuD:YES hiddenView:nil successfulBlock:^(id responseObject) {
                
                for (NSDictionary *dic in responseObject) {
                    if (![[dic objectForKey:@"start_date"] isKindOfClass:[NSNull class]]) {
                        if ([[dic objectForKey:@"start_date"] hasPrefix:strDate]) {
                            EntertainmentModel *enter = [EntertainmentModel enterWithDictionary:dic];
                            [self.NewArray addObject:enter];
                        }
                    }
                }
                [self.tableView reloadData];
            } failureBlock:^(NSError *error) {
                NSLog(@"ERROR: %@", error);
            }];
        }

    }
    
    
}

-(void)loadNewData
{
    [self.enterModelArray removeAllObjects];
    self.dataPage = 1;
    [self loadData];
    [self.tableView reloadData];
}
-(void)loadMoreData
{
    _dataPage += 1;
    [self loadData];
}

#pragma mark 创建TableView
-(void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 104 * kHeight, self.view.frame.size.width, self.view.frame.size.height - 154 * kHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    [self.tableView registerClass:[EnterTableViewCell class] forCellReuseIdentifier:@"EnterTableViewCell"];
    
    if (self.index == 1) {
        //下拉刷新
        self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        [self.tableView.header beginRefreshing];
        
        //下拉加载
        self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        self.tableView.footer = self.footer;
    }
    
}

//返回行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 220 * kHeight;
}

//返回行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.index == 1) {
         return self.enterModelArray.count;
    }
    else
    {
         return self.NewArray.count;
    }
   
}

//重用机制
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EnterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EnterTableViewCell" forIndexPath:indexPath];
    if (self.index == 1) {
       cell.enterModel = self.enterModelArray[indexPath.row];
    }else
    {
       cell.enterModel = self.NewArray[indexPath.row];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

//点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EnterDetailViewController *detail = [[EnterDetailViewController alloc]init];
    if (self.index ==1 ) {
        detail.enterModel = self.enterModelArray[indexPath.row];
    }else
    {
       detail.enterModel = self.NewArray[indexPath.row];
    }
    
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:detail animated:YES];
    [self setHidesBottomBarWhenPushed:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
